<?php


class Link
{
    function __construct($db,$req)
    {
        $this->db = $db;
        $this->req = $req;
    }
    function json($sta,$data){
        return json_encode(array('status'=>$sta,'msg'=>$data));
    }
    function add(){
        date_default_timezone_set('prc');
        $name = $this->req['name'];
        $url = $this->req['url'];
        $file = $_FILES['file'];
        $t = time();
        $time = date('Y-m-d H:i:s',time());
        $extname = explode('.',$file['name'])[1];
        $_temp = $file['tmp_name'];
        move_uploaded_file($_temp,'./static/' . $t . '.' . $extname);
        $path = '/boke/static/' . $t . '.' . $extname;
        $this->db->query('insert into link(name,url,time,pjname) values (?,?,?,?)',$name,$url,$time,$path);
        echo $this->json(200,'增加成功');
    }

    function find(){
        $all = $this->db->query("select * from link order by id desc ");
        echo json_encode(array('status'=>200,'msg'=>$all));
    }
    function del(){
        @ $id = $this->req['id'];
        if(empty($id)){
            exit($this->json(500,'必须传入id'));
        }else{
            $this->db->query('delete from link where id=?',$id);
            echo $this->json(200,'删除成功');
        }
    }
    function edit(){
        date_default_timezone_set('prc');
        $name = $this->req['name'];
        $id = $this->req['id'];
        $url = $this->req['url'];
        @ $file = $_FILES['file'];
        $time = date('Y-m-d H:i:s',time());
        if(empty($file)){
            $pjname = $this->req['pjname'];
        }else{
            $t = time();
            $extname = explode('.',$file['name'])[1];
            $_temp = $file['tmp_name'];
            move_uploaded_file($_temp,'./static/' . $t . '.' . $extname);
            $pjname = '/boke/static/' . $t . '.' . $extname;
        }
        $this->db->query('update link set name=?,url=?,time=?,pjname=? where id=?',$name,$url,$time,$pjname,$id);
        echo $this->json(200,'编辑成功');
    }
}